<?php
/**
 * Created By PhpStorm
 * Author: patrick wu
 * Date: 2020/11/08
 * Time: 11:21
 */
namespace App\Jobs;

use Carbon\Carbon;
use Illuminate\Bus\Queueable;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Foundation\Bus\Dispatchable;
use Illuminate\Queue\InteractsWithQueue;
use Illuminate\Queue\SerializesModels;
use App\Http\Model\Mysql\ShopModel;
use Illuminate\Support\Facades\Storage;
use App\Http\Model\Mysql\OrderModel;

class AutoCancelJob implements ShouldQueue
{
    use Dispatchable, InteractsWithQueue, Queueable, SerializesModels;

    public $order;

    /**
     * Create a new job instance.
     *
     * @return void
     */
    public function __construct(OrderModel $order)
    {
        //查看店铺自动取消时间
        $cancel_time    =   ShopModel::where(['id' => 1])->value('auto_cancel_time') ?? 3600;
        $this->delay($cancel_time);
        $this->order    =   $order;
    }

    /**
     * Execute the job.
     *
     * @return void
     */
    public function handle()
    {
        /**
         * 判断该订单是否已经支付
         */
        if ($this->order->is_pay != OrderModel::IS_PAY) {
            OrderModel::where(['id' => $this->order->id])->update(['order_status' => OrderModel::IS_CANCEL]);
            $file_path  =   'auto_cancel_job_' . Carbon::now()->format('Y_m_d') . '.txt';
            Storage::append($file_path, Carbon::now()->toDateTimeString() . ': 订单号：' . $this->order->order_no . '自动取消');
        }
    }

    public function fail($exception = null)
    {
        //
        $file_path  =   'auto_cancel_job_' . Carbon::now()->format('Y_m_d') . '.txt';
        Storage::append($file_path, Carbon::now()->toDateTimeString() . ': ' . $this->order->order_no . '自动取消错误, 错误信息：' . ($exception->getMessage() ?? '取消错误'));
    }
}
